package com.soft.idc.common.control;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.ICallback;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.render.CaptchaRender;
import com.soft.idc.common.model.IdcUser;
import com.soft.idc.common.service.IdcRoleService;
import com.soft.idc.common.util.JQPage;
import com.soft.idc.common.vo.CacheVo;

public class CacheController extends Controller {

	private static final Logger log = Logger.getLogger(CacheController.class);

	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public void put() {
		HttpServletRequest request = this.getRequest();
		InputStream is = null;
		try {
			request.setCharacterEncoding("UTF-8");
			int size = request.getContentLength();

			is = request.getInputStream();

			byte[] reqBodyBytes = readBytes(is, size);
			String res = new String(reqBodyBytes);

			Map<String, String> value = (Map<String, String>) JsonKit.parse(res, Map.class);

			CacheVo vo = new CacheVo();
			vo.setCache_name(value.get("cache_name"));
			vo.setKey(value.get("key"));
			vo.setValue(value.get("value"));
			vo.setCreate_time(value.get("create_time"));

			String flag = value.get("flag");// 覆盖标志

			if (flag != null && "1".equals(flag)) {// 时间大于
				CacheVo oldVo = CacheKit.get(vo.getCache_name(), vo.getKey());
				if (oldVo != null) {
					String createTime0 = oldVo.getCreate_time();
					Date oldDate = null;
					Date newDate = null;
					try {
						oldDate = format.parse(createTime0);
						newDate = format.parse(vo.getCreate_time());
					} catch (ParseException e) {
						e.printStackTrace();
					}
					if (newDate.getTime() > oldDate.getTime()) {
						CacheKit.put(vo.getCache_name(), vo.getKey(), vo);
					}else{
						log.warn("put cache is not the newest obj...");
					}
				} else {
					CacheKit.put(vo.getCache_name(), vo.getKey(), vo);
				}
			} else {
				CacheKit.put(vo.getCache_name(), vo.getKey(), vo);
			}

			// log.info("content >> " + vo.getKey());
			this.setAttr("result", "0");
			this.renderJson();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("set cache exception：" + e.getMessage());
			this.setAttr("result", -1);
			this.setAttr("desc", e.getMessage());
			this.renderJson();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public void get() {
		String cacheName = this.getPara("cache_name");
		String key = this.getPara("key");
		CacheVo vo = CacheKit.get(cacheName, key);
		Map<String, Object> value = new HashMap<String, Object>();
		if (vo != null) {
			value.put("result", "0");
			value.put("cache", vo);
		} else {
			value.put("result", "-1");
		}
		this.renderJson(value);
	}

	public static final byte[] readBytes(InputStream is, int contentLen) {
		if (contentLen > 0) {
			int readLen = 0;

			int readLengthThisTime = 0;

			byte[] message = new byte[contentLen];

			try {

				while (readLen != contentLen) {

					readLengthThisTime = is.read(message, readLen, contentLen - readLen);

					if (readLengthThisTime == -1) {// Should not happen.
						break;
					}

					readLen += readLengthThisTime;
				}

				return message;
			} catch (IOException e) {
				// Ignore
				// e.printStackTrace();
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

		return new byte[] {};
	}

}
